package billing.image.servlet;

import java.awt.image.BufferedImage;
import java.util.List;
import java.util.Vector;

import billing.image.bean.ConfigCenter;
import billing.image.bean.ImageBean;
import billing.image.bean.PhotoUriParaser;
import billing.image.bean.SizeConfig;
import billing.image.control.ControlCenter;
import billing.image.utils.StringUtils;
import billing.imglib.image.*;

public class PublicServlet extends ImageServlet{
	private static final long serialVersionUID = 669L;
	
//	protected byte[] generateImage(PhotoUriParaser paraser)
//			throws IOException {
//		String key = paraser.getType()+"#" + paraser.getPhotoSign();
//		SizeConfig config = ConfigCenter.getSizeConfig(key);
//		if(null != config){
//			String filePath = ControlCenter.getFilePath(paraser, config);
//			//return getFileBytes(filePath);
//		    ImageBean image = new ImageBean(filePath);
//		    ImageFilter imageMng = new ScaleFilter(image.getWidth(),image.getHeight());
//		}else if(StringUtils.isBlank(paraser.getPhotoSign())){
//			String filePath = ControlCenter.getFilePath(paraser, config);
//			return getFileBytes(filePath);
//		}
//		return null;
//	}
//	
//	private  byte[] getFileBytes(String filePath) throws IOException{
//		File file = new File(filePath);
//		if(file.exists()){
//			return FileUtils.readFileToByteArray(file);
//		}
//		return null;
//	}

	@Override
	public ImageBean execute(PhotoUriParaser paraser) {
		String key = paraser.getType()+"#" + paraser.getPhotoSign();
		SizeConfig config = ConfigCenter.getSizeConfig(key);
		ImageBean result = null;
		if(null != config){
			String filePath = ControlCenter.getFilePath(paraser, config);
		    result = new ImageBean(filePath);
		    ImageFilter imageFilter = null;
		    List<ImageFilter> filterList = new Vector<ImageFilter>();
		    
		    imageFilter = new BicubicScaleFilter(config.getWidth(), config.getHeight());
		    filterList.add(imageFilter);
		    
		    
		    BufferedImage temp = process(result.getBufferedImage(), filterList);
		    result.setBufferedImage(temp);
		}else if(StringUtils.isBlank(paraser.getPhotoSign())){
			String filePath = ControlCenter.getFilePath(paraser, config);
			result = new ImageBean(filePath);
		}
		return result;
	}
	
	
	
	
	private BufferedImage process(BufferedImage src ,List<ImageFilter> filterList){
		BufferedImage result = src;
		for (ImageFilter imageFilter : filterList) {
			result = imageFilter.filter(result, null);
		}
		return result;
	}
}
